import {
  delDataRelatedReq,
  getDataRelatedsDagReq,
  getDataRelatedsReq
} from '@/service/modules/data-manage'
import {
  DataRelatedNode,
  DataRelatedNodeRelation,
  TableDataRelated
} from '@/service/modules/data-manage/types'
import { reactive } from 'vue'

export function useTable() {
  const state = reactive({
    datasourceId: 0,
    dbName: '',
    tableName: '',
    depth: 1,
    upstreamRelated: Array<TableDataRelated>(),
    downstreamRelated: Array<TableDataRelated>(),
    edges: Array<DataRelatedNodeRelation>(),
    nodes: Array<DataRelatedNode>(),
    loading: false,
    dagLoading: false,
    currentRecord: {} as TableDataRelated
  })

  const getDataRelateds = async () => {
    if (state.loading) return
    state.loading = true
    const res = await getDataRelatedsReq({
      datasourceId: state.datasourceId,
      dbName: state.dbName,
      tableName: state.tableName
    })
    state.loading = false
    if (res.resp_code === 0) {
      state.upstreamRelated = res.data.upstream
      state.downstreamRelated = res.data.downstream
    }
  }
  const getDataRelatedsDag = async () => {
    if (state.dagLoading) return
    state.dagLoading = true
    const res = await getDataRelatedsDagReq({
      datasourceId: state.datasourceId,
      dbName: state.dbName,
      tableName: state.tableName,
      depth: state.depth
    })
    state.dagLoading = false
    if (res.resp_code === 0) {
      state.edges = res.data.edges
      state.nodes = res.data.nodes
    }
  }
  const delRelated = async (id: number) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('dataManage.delRelatedTips'),
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delDataRelatedReq({ id: id })
        if (res.resp_code === 0) {
          getDataRelateds()
          getDataRelatedsDag()
        }
      }
    })
  }
  const onOperationClick = (
    data: { rowData: TableDataRelated },
    type: 'delRelated'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'delRelated':
        delRelated(data.rowData.id)
        break
    }
  }

  return {
    state,
    getDataRelateds,
    getDataRelatedsDag,
    onOperationClick
  }
}
